package md.mru.backend.core.dao;

import md.mru.backend.core.dtos.TreeNodeModelDto;
import md.mru.backend.core.dtos.RootTreeModelDto;
import md.mru.backend.core.utils.Constants;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManagerFactory;
import java.io.Serializable;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public class TreeDao implements Serializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(TreeDao.class);

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    //DosarDaoImp dosarDAO = new DosarDaoImp();

    /**
     * @param nodeId
     * @param dosar  -- if true - return dosar id , else return record id from
     *               tree_dosar_lnk
     * @return
     */
    public Integer dosarNode(Integer nodeId, Boolean dosar) {
        Connection con = null;
        try {
            String query = "select " + Constants.treeDosarLnk_Id + " , " + Constants.treeDosarLnk_DsrId + " "
                    + "from " + Constants.treeDosarLnk_TableName
                    + " WHERE "
                    + "(" + Constants.treeDosarLnk_TreId + " = " + nodeId + " AND SYSDATE >= " + Constants.treeDosarLnk_VldFrm + " AND SYSDATE < NVL(" + Constants.treeDosarLnk_VldTo + " , SYSDATE + 1) AND " + Constants.treeDosarLnk_Ste + " = 1)";
            LOGGER.debug("SQL = " + query);
            con = getHibernateConnection();
            PreparedStatement ps = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            Integer id = null;
            int counter = 0;
            while (rs.next()) {
                if (dosar) {
                    id = rs.getInt(Constants.treeDosarLnk_DsrId);
                } else {
                    id = rs.getInt(Constants.treeDosarLnk_Id);
                }

                counter++;
            }

            if (counter == 1) {
//                LOGGER.debug( "Found DOSAR [" + id + "] for NODE " + nodeId);
                return id;
            } else if (counter > 1) {
                System.err.println("More that one row!!!");
                return -1;
            } else if (counter == 0) {
//                LOGGER.debug( "No DOSARS found for NODE " + nodeId);
                return 0;
            } else {
                System.err.println("Some bad hapening :)");
                return -1;
            }

        } catch (Exception ex) {
            System.err.println("Eroare dosarNode: " + ex);
            return -1;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.print("Eroare finally dosarNode: " + e);
                }
            }
        }
    }

    public Integer findDosarForNode(Integer id) {
        return dosarNode(id, true);
    }

    public Integer findNodeForDosar(Integer id) {
        return dosarNode(id, false);
    }

    /*public List<Dosar> findFreeDOsars() {
        Connection con = null;
        try {
            String query = "SELECT " + Constants.dsr_Id + " FROM " + Constants.dsr_TableName + " "
                    + "WHERE " + Constants.dsr_Id + " not in ( "
                    + "select  " + Constants.treeDosarLnk_DsrId + " "
                    + "from " + Constants.treeDosarLnk_TableName + " "
                    + "WHERE  SYSDATE < NVL(" + Constants.treeDosarLnk_VldTo + " , SYSDATE + 1) AND ( STE = 1 OR STE = 4 OR STE = 5 OR STE = 6))";
            LOGGER.debug("SQL = " + query);
            con = OracleConnection.getConnection();
            PreparedStatement ps = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            List<Dosar> freeDosars = new ArrayList<Dosar>();
            while (rs.next()) {
                Integer id = rs.getInt("ID");
                Dosar d = dosarDAO.getDosar(id);
                d.setEditable(true);
                freeDosars.add(d);
            }
            return freeDosars;
        } catch (Exception ex) {
            System.err.println("Eroare findFreeDOsars: " + ex);
            return null;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.println("Eroare finally findFreeDOsars: " + e);
                }
            }
        }
    }*/

    public Boolean moveDosar(Integer sourceId, Integer destinationId, Long dosId) {
        return dosarControl(sourceId, destinationId, dosId, false);
    }

    public Boolean outDosar(Integer source) {
        return dosarControl(findNodeForDosar(source), null, null, true);
    }

    public Boolean insertDosar(Integer destinationId, Long dosId) {
        return dosarControl(null, destinationId, dosId, false);
    }

    public Boolean dosarControl(Integer sourceId, Integer destinationId, Long dosId, Boolean out) {
        Connection con = null;
        try {
            con = getHibernateConnection();
            con.setAutoCommit(false);
            Statement s = con.createStatement();
            if (sourceId != null || out) {
                String dezactivate = "UPDATE " + Constants.treeDosarLnk_TableName + " SET " + Constants.treeDosarLnk_Ste + " = 0 , " + Constants.treeDosarLnk_VldTo + " = SYSDATE WHERE " + Constants.treeDosarLnk_Id + " = " + sourceId;
                s.executeUpdate(dezactivate);
                LOGGER.debug("Dosar dezactivated: " + dezactivate);
            }
            if (!out) {
                String move = "INSERT INTO " + Constants.treeDosarLnk_TableName + " (" + Constants.treeDosarLnk_Id + " , " + Constants.treeDosarLnk_TreId + " , " + Constants.treeDosarLnk_DsrId + " , " + Constants.treeDosarLnk_VldFrm + " , " + Constants.treeDosarLnk_Ste + ") "
                        + "VALUES (" + Constants.treeDosarSeq + ".nextval , " + destinationId + "  , " + dosId + "  , SYSDATE  ,  1  )";
                LOGGER.debug("Dosar moved: " + move);
                s.executeUpdate(move);
            }
            con.commit();
            s.close();
            return true;
        } catch (Exception e) {
            System.err.println("Eroare dosarControl: " + e);
            try {
                con.rollback();
            } catch (SQLException ex) {
                System.err.println("moveDosar error : " + ex);
            }
            return false;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    System.err.println("" + e);
                }
            }

        }
    }

    public TreeNodeModelDto getLastFunctionForDosar(Long id, Boolean dismissed) {
        Connection con = null;
        try {
            String query =
                    "SELECT "
                            + "SYS_CONNECT_BY_PATH(NME, ' > ') PATH ,ID from "
                            + " TRE "
                            + "WHERE ID =  "
                            + "( "
                            + "SELECT TRE_ID FROM "
                            + (dismissed ? " ORD_ARH " : "LNK_TRE_DSR ")
                            + "WHERE ID =  "
                            + "( "
                            + "SELECT MAX(l.ID) FROM "
                            + (dismissed ? " ORD_ARH " : "LNK_TRE_DSR ")
                            + "l "
                            + "LEFT JOIN NML n  "
                            + "ON l.tpe = n.id "
                            + "WHERE (n.tpe = 2 OR n.tpe = 3 OR n.tpe = 5 OR n.tpe = 7) AND DSR_ID = ?"
                            + ") "
                            + ") "
                            + "start with ID = 0 "
                            + "connect by prior ID = PID";
            LOGGER.debug("SQL = " + query);
            con = getHibernateConnection();
            PreparedStatement ps = con.prepareStatement(query);
            ps.setLong(1, id);
            ResultSet rs = ps.executeQuery();
            TreeNodeModelDto nod = new TreeNodeModelDto();
            while (rs.next()) {
                nod.setId(rs.getInt("ID"));
                nod.setPath(rs.getString("PATH"));
            }
            return nod;
        } catch (Exception ex) {
            System.err.println("Eroare getFunctionForNode: " + ex);
            return null;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.println("Eroare finally getFunctionForNode: " + e);
                }
            }
        }
    }

    public TreeNodeModelDto getNode(Integer id) {
        Connection con = null;
        try {
            String query = "select NME , DSC , TRE_TPE , TEL1 , TEL2 , TEL3 , VLD_FRM , VLD_TO , FVR from tre where id = " + id;
            LOGGER.debug("SQL = " + query);
            con = getHibernateConnection();
            PreparedStatement ps = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            TreeNodeModelDto nod = new TreeNodeModelDto();
            while (rs.next()) {
                nod.setName(rs.getString("NME"));
                nod.setDescription(rs.getString("DSC"));
                nod.setTpeId(rs.getInt("TRE_TPE"));
                nod.setTel1(rs.getString("TEL1"));
                nod.setTel2(rs.getString("TEL2"));
                nod.setTel3(rs.getString("TEL3"));
                nod.setVldFrm(rs.getDate("VLD_FRM"));
                nod.setVldTo(rs.getDate("VLD_TO"));
                nod.setPosition(rs.getDouble("FVR"));
            }
            return nod;
        } catch (Exception ex) {
            System.err.println("Eroare getNodeNmeAndDsc: " + ex);
            return null;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.println("Eroare finally getNodeNmeAndDsc: " + e);
                }
            }
        }
    }

    public Boolean addNode(TreeNodeModelDto nod, TreeNodeModelDto currentNod) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = getHibernateConnection();
            con.setAutoCommit(false);


            String addNode = "INSERT INTO "
                    + "TRE "
                    + "(ID , PID , NME , DSC , TRE_TPE , TEL1 , TEL2 , TEL3 , FVR , VLD_FRM , VLD_TO) "
                    + "VALUES (TRE_SEQ.NEXTVAL , ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)";

            pstmt = con.prepareStatement(addNode);

            pstmt.setLong(1, currentNod.getId());
            pstmt.setString(2, nod.getName());
            pstmt.setString(3, nod.getDescription());
            pstmt.setInt(4, nod.getTpeId());
            pstmt.setString(5, nod.getTel1());
            pstmt.setString(6, nod.getTel2());
            pstmt.setString(7, nod.getTel3());
            pstmt.setDouble(8, nod.getPosition() == null ? 0 : nod.getPosition());
            pstmt.setDate(9, new Date(nod.getVldFrm().getTime()));
            pstmt.setDate(10, nod.getVldTo() == null ? null : new Date(nod.getVldTo().getTime()));

            LOGGER.debug("Add node: " + addNode);
            pstmt.executeUpdate();

            con.commit();

            return true;
        } catch (Exception e) {
            System.err.println("Eroare addNode:" + e);
            try {
                con.rollback();
            } catch (SQLException ex) {
                System.err.println("[addNode] Eroor:" + ex);
            }
            return false;
        } finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                con.close();
            } catch (SQLException ex) {
                System.err.println("[addNode] finally Eroor:" + ex);
            }
        }

    }

    public Boolean updateNode(TreeNodeModelDto nod, Integer id) {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = getHibernateConnection();
            con.setAutoCommit(false);

            String query = "UPDATE TRE SET NME = ? , DSC = ? , TEL1 = ? , TEL2 = ? , TEL3 = ? , TRE_TPE = ? , VLD_FRM = ? , VLD_TO = ? , FVR = ? WHERE ID = " + id;
            pstmt = con.prepareStatement(query);

            pstmt.setString(1, nod.getName());
            pstmt.setString(2, nod.getDescription());
            pstmt.setString(3, nod.getTel1());
            pstmt.setString(4, nod.getTel2());
            pstmt.setString(5, nod.getTel3());
            pstmt.setInt(6, nod.getTpeId());
            pstmt.setDate(7, new Date(nod.getVldFrm().getTime()));
            pstmt.setDate(8, nod.getVldTo() == null ? null : new Date(nod.getVldTo().getTime()));
            pstmt.setDouble(9, nod.getPosition());

            LOGGER.debug("Update node: " + query);
            pstmt.executeUpdate();

            con.commit();

            return true;
        } catch (Exception e) {
            System.err.println("Eroare updateNode:" + e);
            try {
                con.rollback();
            } catch (SQLException ex) {
                System.err.println("[updateNode] Eroor:" + ex);
            }
            return false;
        } finally {
            try {
                if (pstmt != null) {
                    pstmt.close();
                }
                con.close();
            } catch (SQLException ex) {
                System.err.println("[updateNode] finally Eroor:" + ex);
            }
        }

    }

    private void expandAllParents(TreeNode tn) {
        if (tn.getParent() != null) {
            tn.setExpanded(true);
            expandAllParents(tn.getParent());
        }
    }

    private void propagateEroor(TreeNode tn) {
        if (tn.getParent() != null) {
            ((TreeNodeModelDto) tn.getData()).setError(true);
            propagateEroor(tn.getParent());
        }
    }

    public List<Integer> getNodesForGrp(long grpId) {
        List<Integer> nodes = new ArrayList<Integer>();
        Connection con = null;
        try {
            String query = "SELECT TREE_ID FROM tree_grp_lnk WHERE grp_id = " + grpId;
            LOGGER.debug("SQL = " + query);
            con = getHibernateConnection();
            PreparedStatement ps = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Integer grp = rs.getInt("TREE_ID");
                nodes.add(grp);
            }
            return nodes;
        } catch (Exception ex) {
            System.err.println("Eroare getNodesForGrp: " + ex);
            return nodes;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.println("Eroare finally getNodesForGrp: " + e);
                }
            }
        }
    }

    public List<Integer> _getUserNodes(String user) {
        List<Integer> nodes = new ArrayList<Integer>();
        Connection con = null;
        try {
            String query = "SELECT TREE_ID FROM tree_grp_lnk WHERE grp_id IN (SELECT GRP_ID FROM USR_GRP_LNK WHERE USR_ID =(SELECT ID FROM USR WHERE NME = '" + user + "'))";
            LOGGER.debug("SQL = " + query);
            con = getHibernateConnection();
            PreparedStatement ps = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Integer grp = rs.getInt("TREE_ID");
                nodes.add(grp);
            }
            return nodes;
        } catch (Exception ex) {
            System.err.println("Eroare getUserNodes: " + ex);
            return nodes;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.println("Eroare finally getUserNodes: " + e);
                }
            }
        }
    }

    public Integer isNodeEngaged(Integer nodeId) {
        String query = "SELECT dsr_id"
                + " FROM lnk_tre_dsr lnk"
                + " LEFT JOIN DOSAR dos"
                + " ON lnk.dsr_id = dos.id"
                + " WHERE "
                + " TRE_ID = ? AND SYSDATE >= VLD_FRM AND SYSDATE < NVL(VLD_TO , SYSDATE + 1) AND lnk.STE = 1 AND (dos.ste = 3 OR dos.ste = 7)";
        Connection con = null;
        try {
            LOGGER.debug("SQL = " + query);
            con = getHibernateConnection();
            PreparedStatement ps = con.prepareStatement(query);
            ps.setInt(1, nodeId);
            ResultSet rs = ps.executeQuery();
            Integer counter = 0;
            while (rs.next()) {
                counter++;
            }
            return counter;
        } catch (Exception ex) {
            System.err.println("Eroare isNodeEngaged: " + ex);
            return -1;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.println("Eroare finally isNodeEngaged: " + e);
                }
            }
        }
    }

    public RootTreeModelDto getRootView() {
        return getRoot(null, null, false);
    }

    public RootTreeModelDto getRootFind(Long dosarId) {
        return getRoot(dosarId, null, false);
    }

    public RootTreeModelDto getRootAdmin() {
        return getRoot(null, null, true);
    }

    public RootTreeModelDto getRootAdminForGroup(Long groupId) {
        return getRoot(null, groupId, true);
    }

    public RootTreeModelDto getRoot(Long dosarId, Long groupID, Boolean admin) {
        String loggedUser = "1";

        Connection con = null;
        TreeNodeModelDto obj;
        TreeNode root = null;
        RootTreeModelDto rootT = new RootTreeModelDto();
        //List<Integer> nodes = getUserNodes(TreeBean.getLoggedUser());
        List<Integer> grpNodes = null;
        if (groupID != null) {
            grpNodes = getNodesForGrp(groupID);
        }

        try {
            List<TreeNode> stack = new ArrayList<TreeNode>();

            String query = "SELECT  tre_tpe"
                    + " , frs FRS"
                    + " , lst LST"
                    + " , dsr_ste";
            if (admin) {
                query += " , 0 as DSR_ID";
            } else {
                query += " ,  DSR_ID";
            }
            query += " , LPAD(' ',6*(LEVEL- 1)) || TO_CHAR( NME) AS NMS"
                    + " , DSC , NME AS NAMEX"
                    + " , LEVEL, source_.ID ID, TEL1 , TEL2 , TEL3     "
                    + " ,  PID, SYS_CONNECT_BY_PATH(source_.ID, ',') PARENTS"
                    + " , SYS_CONNECT_BY_PATH(NME,' > ') PARENTSDSC     "
                    + " , CONNECT_BY_ISLEAF AS ISLEAF  , TPE_NME , TPE_ICO , TPE_ID , NOD_TPE , fvr , steDNME"
                    + " FROM "
                    + " ("
                    + "       SELECT T.*, lnk.*"
                    + "        from      "
                    + "         ( select tt.id,pid,TEL1 , TEL2 , TEL3 , tt.nme, dsc, tt.fvr,NF.ICO AS TPE_ICO , nf.nme as TPE_NME, NF.TPE AS TPE_ID , NF.ID NOD_TPE  from TRE tt"
                    + "             LEFT JOIN NML_FNC NF ON TT.TRE_TPE = NF.ID "
                    + "          WHERE tt.vld_frm <= sysdate AND  sysdate <= NVL(tt.vld_to , sysdate+1)";

            if (admin) {
            } else {
                query += "             and (tt.id in (select tree_id from tree_grp_lnk where grp_id in (select grp_id from usr_grp_lnk where usr_id=(SELECT ID FROM USR WHERE NME = '" + loggedUser + "'))) or tt.id=0 )";
            }
            query += "          ) T"
                    + "          left join "
                    + "          ("
                    + "                 select TRE_ID,DSR_ID,FRS,LST,dosar.ste dsr_ste , sted.nme steDNME , sted.tre_tpe from  LNK_TRE_DSR lnkx LEFT JOIN dosar  on dosar.ID = lnkx.dsr_id"
                    + " LEFT JOIN NML_STE steD on steD.id = dosar.ste"
                    + "                 WHERE ( SYSDATE >= VLD_FRM AND SYSDATE < NVL(VLD_TO , SYSDATE + 1) AND lnkx.STE = 1)"
                    + "          ) lnk on lnk.tre_id=t.id"
                    + " )source_"
                    + " START WITH source_.ID = 0 "
                    + " CONNECT BY NOCYCLE PRIOR source_.ID = source_.PID "
                    + " ORDER SIBLINGS BY FVR , ID  ,DSR_STE ,  TRE_TPE";
            LOGGER.debug("Tree Root sql: " + query);

            //List resultList = entityManagerFactory.createEntityManager().createNativeQuery(query).getResultList();


            con = getHibernateConnection();

            PreparedStatement ps = con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            boolean first = false;
            TreeNode lastTreeNode = null;

            while (rs.next()) {
                Integer treTpe = rs.getInt("tre_tpe");
                Long idX = rs.getLong("DSR_ID");

                if (lastTreeNode == null || (lastTreeNode.getData() != null && ((TreeNodeModelDto) lastTreeNode.getData()).getId() != rs.getInt("ID")) || (((TreeNodeModelDto) lastTreeNode.getData()).getId() == rs.getInt("ID") && ((TreeNodeModelDto) lastTreeNode.getData()).getFolderId() != idX && (rs.getInt("dsr_ste") == 3 || rs.getInt("dsr_ste") == 7))) {
                    obj = new TreeNodeModelDto();
                    if (lastTreeNode != null && lastTreeNode.getData() != null && ((TreeNodeModelDto) lastTreeNode.getData()).getId() == rs.getInt("ID") && ((TreeNodeModelDto) lastTreeNode.getData()).getFolderId() != idX && (rs.getInt("dsr_ste") == 3 || rs.getInt("dsr_ste") == 7)) {
                        LOGGER.error("Depistat eroare la nod : " + rs.getInt("ID"));
                        obj.setError(true);
                    }
                    obj.setId(rs.getInt("ID"));
                    obj.setPid(rs.getInt("PID"));
                    obj.setName(rs.getString("nameX"));
                    obj.setDescription(rs.getString("DSC"));
                    obj.setLevel(rs.getInt("level"));
                    obj.setPath(rs.getString("parentsDsc"));
                    obj.setTpeId(rs.getInt("TPE_ID"));
                    obj.setTpeNme(rs.getString("TPE_NME"));
                    obj.setTpeIco(rs.getString("TPE_ICO"));
                    obj.setNodTpe(rs.getInt("NOD_TPE"));
                    obj.setTel1(rs.getString("TEL1"));
                    obj.setTel2(rs.getString("TEL2"));
                    obj.setTel3(rs.getString("TEL3"));
                    obj.setPosition(rs.getDouble("FVR"));
                    obj.setSte(rs.getInt("dsr_ste"));


                    //if (rs.getInt("dsr_ste") == 3 || rs.getInt("dsr_ste") == 7) {
                    if (treTpe == 1) {
                        if (idX != null && idX != 0) {
                            obj.setFolderId(idX);
                            obj.setFirstName(rs.getString("FRS"));
                            obj.setLastName(rs.getString("LST"));
                        }
                    }

                    if (!first) {
                        if (obj.getId() == 0) {
                            root = new DefaultTreeNode(obj, null);
                            stack.add(root);
                        } else {
                            root = new DefaultTreeNode("ROOT", null);
                            stack.add(root);
                            TreeNode child = new DefaultTreeNode(obj, root);
                            stack.add(child);
                        }
                        first = true;
                        continue;
                    }

                    int stakSize = stack.size();
                    if (((TreeNodeModelDto) ((DefaultTreeNode) stack.get(stack.size() - 1)).getData()).getLevel() < obj.getLevel()) {
                        lastTreeNode = new DefaultTreeNode(obj, (DefaultTreeNode) stack.get(stack.size() - 1));
                        if (grpNodes != null && grpNodes.contains(obj.getId())) {
                            lastTreeNode.setSelected(true);
                        }
                        stack.add(lastTreeNode);

                        /*add */
                        //if (rs.getInt("dsr_ste") != 3 && rs.getInt("dsr_ste") != 7 && idX != null && idX != 0) {
                        if (treTpe != 1 && idX != null && idX != 0) {
                            obj = new TreeNodeModelDto();
                            obj.setId(rs.getInt("ID"));
                            obj.setFolderId(rs.getLong("DSR_ID"));
                            obj.setFirstName(rs.getString("FRS"));
                            obj.setLastName(rs.getString("LST"));
                            obj.setName(rs.getString("steDNME"));
                            obj.setTpeIco("ui-icon-person");
                            obj.setTpeId(rs.getInt("TPE_ID"));
                            obj.setSte(rs.getInt("dsr_ste"));
                            obj.setNodTpe(rs.getInt("NOD_TPE"));
                            obj.setStyleClass("maternityNode");
                            obj.setFolderStyleClass("inactivePerson");
                            TreeNode child = new DefaultTreeNode(obj, lastTreeNode); //
                        }


                        if (obj.getFolderId() != null && dosarId != null && obj.getFolderId().longValue() == dosarId.longValue()) {
                            lastTreeNode.setSelected(true);
                            rootT.setSelectedNode(lastTreeNode);
                            expandAllParents(lastTreeNode);
                        }

                        if (obj.getError()) {
                            propagateEroor(lastTreeNode);
                        }
                        continue;
                    }

                    if (((TreeNodeModelDto) ((DefaultTreeNode) stack.get(stack.size() - 1)).getData()).getLevel() == obj.getLevel()) {
                        if (stack.size() > 1) {
                            stack.remove(stack.size() - 1);
                        }
                        lastTreeNode = new DefaultTreeNode(obj, (DefaultTreeNode) stack.get(stack.size() - 1));
                        if (grpNodes != null && grpNodes.contains(obj.getId())) {
                            lastTreeNode.setSelected(true);
                        }
                        stack.add(lastTreeNode);
                        /*add */
                        //if (rs.getInt("dsr_ste") != 3 && rs.getInt("dsr_ste") != 7 && idX != null && idX != 0) {
                        if (treTpe != 1 && idX != null && idX != 0) {
                            obj = new TreeNodeModelDto();
                            obj.setId(rs.getInt("ID"));
                            obj.setFolderId(rs.getLong("DSR_ID"));
                            obj.setFirstName(rs.getString("FRS"));
                            obj.setLastName(rs.getString("LST"));
                            obj.setName(rs.getString("steDNME"));
                            obj.setTpeIco("ui-icon-person");
                            obj.setTpeId(rs.getInt("TPE_ID"));
                            obj.setSte(rs.getInt("dsr_ste"));
                            obj.setNodTpe(rs.getInt("NOD_TPE"));
                            obj.setStyleClass("maternityNode");
                            obj.setFolderStyleClass("inactivePerson");
                            TreeNode child = new DefaultTreeNode(obj, lastTreeNode); //
                        }


                        if (obj.getFolderId() != null && dosarId != null && obj.getFolderId().longValue() == dosarId.longValue()) {
                            lastTreeNode.setSelected(true);
                            rootT.setSelectedNode(lastTreeNode);
                            expandAllParents(lastTreeNode);
                        }
                        if (obj.getError()) {
                            propagateEroor(lastTreeNode);
                        }

                        continue;
                    }

                    if (((TreeNodeModelDto) ((DefaultTreeNode) stack.get(stack.size() - 1)).getData()).getLevel() > obj.getLevel()) {
                        boolean bExist = true;
                        while (bExist) {
                            if (((TreeNodeModelDto) ((DefaultTreeNode) stack.get(stack.size() - 1)).getData()).getId() != obj.getPid()) {
                                if (stack.size() == 1) {
                                    break;
                                }
                                stack.remove(stack.size() - 1);
                            } else {
                                break;
                            }
                        }
                        lastTreeNode = new DefaultTreeNode(obj, (DefaultTreeNode) stack.get(stack.size() - 1));
                        if (grpNodes != null && grpNodes.contains(obj.getId())) {
                            lastTreeNode.setSelected(true);
                        }
                        stack.add(lastTreeNode);

                        /*add */
                        //if (rs.getInt("dsr_ste") != 3 && rs.getInt("dsr_ste") != 7 && idX != null && idX != 0) {
                        if (treTpe != 1 && idX != null && idX != 0) {
                            obj = new TreeNodeModelDto();
                            obj.setId(rs.getInt("ID"));
                            obj.setFolderId(rs.getLong("DSR_ID"));
                            obj.setFirstName(rs.getString("FRS"));
                            obj.setLastName(rs.getString("LST"));
                            obj.setName(rs.getString("steDNME"));
                            obj.setTpeIco("ui-icon-person");
                            obj.setTpeId(rs.getInt("TPE_ID"));
                            obj.setSte(rs.getInt("dsr_ste"));
                            obj.setNodTpe(rs.getInt("NOD_TPE"));
                            obj.setStyleClass("maternityNode");
                            obj.setFolderStyleClass("inactivePerson");
                            TreeNode child = new DefaultTreeNode(obj, lastTreeNode); //
                        }

                        if (obj.getFolderId() != null && dosarId != null && obj.getFolderId().longValue() == dosarId.longValue()) {
                            lastTreeNode.setSelected(true);
                            rootT.setSelectedNode(lastTreeNode);
                            expandAllParents(lastTreeNode);
                        }
                        if (obj.getError()) {
                            propagateEroor(lastTreeNode);
                        }
                        continue;
                    }
                } else {

                    if (!admin && lastTreeNode != null && lastTreeNode.getData() != null && ((TreeNodeModelDto) lastTreeNode.getData()).getId() == rs.getInt("ID")) {
                        obj = new TreeNodeModelDto();
                        obj.setId(rs.getInt("ID"));
                        obj.setFolderId(rs.getLong("DSR_ID"));
                        obj.setFirstName(rs.getString("FRS"));
                        obj.setLastName(rs.getString("LST"));
                        obj.setName(rs.getString("steDNME"));
                        obj.setTpeIco("ui-icon-person");
                        obj.setTpeId(rs.getInt("TPE_ID"));
                        obj.setSte(rs.getInt("dsr_ste"));
                        obj.setNodTpe(rs.getInt("NOD_TPE"));
                        obj.setStyleClass("maternityNode");
                        obj.setFolderStyleClass("inactivePerson");
                        TreeNode child = new DefaultTreeNode(obj, lastTreeNode); //

                        if (obj.getFolderId() != null && dosarId != null && obj.getFolderId().longValue() == dosarId.longValue()) {
                            child.setSelected(true);
                            rootT.setSelectedNode(child);
                            expandAllParents(child);
                        }

                    }
                }

            }
            rootT.setRoot(root);
            return rootT;
        } catch (Exception ex) {
            System.err.println("Eroare getRoot: " + ex);
            return null;
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (Exception e) {
                    System.err.println("Eroare getRoot: " + e);
                }
            }
        }
    }

    public Connection getHibernateConnection() {
        return null;
    }

}
